package com.probos.bosnatuur.monitor;

import java.util.ArrayList;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import com.google.android.maps.OverlayItem;

public class BosNatuurOverlay extends ItemizedOverlay<BosNatuurOverlayItem> {
	
	private static final int ELEMENT_EDIT=1;
    	
	private ArrayList<BosNatuurOverlayItem> mItems = new ArrayList<BosNatuurOverlayItem>();
	private Context mContext;
	private MapView mMap;

	private Drawable marker=null;
	private BosNatuurOverlayItem inDrag=null;
	private ImageView dragImage=null;
	private int xDragImageOffset=0;
	private int yDragImageOffset=0;
	private int xDragTouchOffset=0;
	private int yDragTouchOffset=0;
	
	private boolean dragStart = false;
	
//	public BosNatuurOverlay(Drawable defaultMarker) {
//		super(boundCenter(defaultMarker));
//	}

	public BosNatuurOverlay(Drawable defaultMarker, Context context) {
		super(boundCenter(defaultMarker));
		mContext = context;
		MapActivity act = (MapActivity) mContext;
		mMap = (MapView) act.findViewById(R.id.mapview);
		marker = defaultMarker;

		dragImage=(ImageView) act.findViewById(R.id.drag);
		
		xDragImageOffset=dragImage.getDrawable().getIntrinsicWidth()/2;
		yDragImageOffset=dragImage.getDrawable().getIntrinsicHeight()/2;
	}
	
	@Override
	protected BosNatuurOverlayItem createItem(int i) {
		return mItems.get(i);
	}

	@Override
	public int size() {
		return mItems.size();
	}

//	public void addItem(BosNatuurOverlayItem item, Drawable marker) {
//		boundCenter(marker);
//		item.setMarker(marker);
//		mItems.add(item);
//		populate();
//	}
	
	public void addItem(BosNatuurOverlayItem item) {
		mItems.add(item);
		populate();
	}

	@Override
	public void draw(Canvas canvas, MapView mapView, boolean shadow) {
		// super.draw(canvas, mapView, shadow);
		
	    if (shadow == false) { 
	        int sz = this.size(); 
	        for (int i = 0; i < sz; i++) { 
	            BosNatuurOverlayItem item = mItems.get(i);                 
	 
	            GeoPoint point = item.getPoint(); 
	            Point ptScreenCoord = new Point(); 
	            mapView.getProjection().toPixels(point, ptScreenCoord); 
	 
	            Paint paint = new Paint(); 
	            paint.setTextAlign(Paint.Align.CENTER); 
//	            paint.setTextSize(10); 
//	            paint.setTypeface(Typeface.DEFAULT_BOLD); 
//	            paint.setShadowLayer(2.0f, 1.0f, 1.0f, Color.DKGRAY); 
//	            paint.setARGB(255, 255, 255, 255); 
	            
	            paint.setColor(item.getColor()); 
	            paint.setTextSize(8); 
	            paint.setFlags(Paint.ANTI_ALIAS_FLAG); 
	            // paint.setTypeface(Typeface.DEFAULT_BOLD);
	            
//	            paint.setStyle(Paint.Style.STROKE);
//	            paint.setARGB(179, 0, 0, 0);
//	            paint.setStrokeWidth(2.0f);
//	            paint.setStrokeCap(Paint.Cap.BUTT);	            

	            canvas.drawCircle(ptScreenCoord.x, ptScreenCoord.y, 6, paint);
	            
	            paint.setColor(Color.WHITE);
	            canvas.drawText(item.getNummer().toString(), ptScreenCoord.x, ptScreenCoord.y+3, paint); 
	        } 
	    } 
	}
	 
	@Override
	protected boolean onTap(int index) {
	  final BosNatuurOverlayItem item = mItems.get(index);
	  AlertDialog.Builder dialog = new AlertDialog.Builder(mContext);
	  dialog.setTitle(item.getTitle());
	  dialog.setMessage(item.getSnippet());
	  dialog.setCancelable(true);
	  dialog.setPositiveButton("Wijzig", new DialogInterface.OnClickListener() {
		  public void onClick(DialogInterface dialog, int which) {
			  editElement(item.getID());
		  }
	  });
	  dialog.setNegativeButton("Sluiten", new DialogInterface.OnClickListener(){
		  public void onClick(DialogInterface dialog, int which){
			  
		  }
	  });
	  dialog.show();
	  return true;
	}
	
	@Override
	public boolean onTouchEvent(MotionEvent event, MapView mapView) {
		final int action=event.getAction();
		final int x=(int)event.getX();
		final int y=(int)event.getY();
		boolean result=false;
		
		if (action==MotionEvent.ACTION_DOWN) {
			for (BosNatuurOverlayItem item : mItems) {
				Point p=new Point(0,0);
				
				mMap.getProjection().toPixels(item.getPoint(), p);
				
				if (hitTest(item, marker, x-p.x, y-p.y)) {
					result=true;
					inDrag=item;
					mItems.remove(inDrag);
					populate();

					xDragTouchOffset=0;
					yDragTouchOffset=0;
					
					setDragImagePosition(p.x, p.y);
					dragImage.setVisibility(View.VISIBLE);

					xDragTouchOffset=x-p.x;
					yDragTouchOffset=y-p.y;
					
					dragStart = false;
					
					break;
				}
			}
		}
		else if (action==MotionEvent.ACTION_MOVE && inDrag!=null) {
			setDragImagePosition(x, y);
			dragStart = true;
			result=true;
		}
		else if (action==MotionEvent.ACTION_UP && inDrag!=null) {
			dragImage.setVisibility(View.GONE);
			
			if (dragStart) {
				
				final String strTitle = inDrag.getTitle();
				final String strSnippet = inDrag.getSnippet();
				final long element_id = inDrag.getID();
				final int kleur = inDrag.getColor();
				final int nummer = inDrag.getNummer();
				
				final BosNatuurOverlayItem drag_item = inDrag;
				
				AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
				builder.setMessage("Wilt u dit punt verplaatsen?")
				       .setCancelable(false)
				       .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
				           public void onClick(DialogInterface dialog, int id) {
				                // MyActivity.this.finish();
								GeoPoint pt = mMap.getProjection().fromPixels(x-xDragTouchOffset, y-yDragTouchOffset);
								BosNatuurOverlayItem toDrop=new BosNatuurOverlayItem(pt, strTitle, strSnippet, element_id, kleur, nummer);
								mItems.add(toDrop);
								populate();
								mMap.invalidate();
								
								ProjectMap act = (ProjectMap) mContext;
								act.updateItem(toDrop);
				           }
				       })
				       .setNegativeButton("No", new DialogInterface.OnClickListener() {
				           public void onClick(DialogInterface dialog, int id) {
				                mItems.add(drag_item);
				                populate();
				                mMap.invalidate();
				                // dialog.cancel();
				           }
				       });
				AlertDialog alert = builder.create();
				alert.show();
				
			} else {
				mItems.add(inDrag);
				populate();
				mMap.invalidate();
				onTap(mItems.indexOf(inDrag));
			}
			
			
			inDrag=null;
			dragStart = false;
			result=true;
		}
		
		return(result || super.onTouchEvent(event, mapView));
	}
	
	private void setDragImagePosition(int x, int y) {
		RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams)dragImage.getLayoutParams();					
		lp.setMargins(x-xDragImageOffset-xDragTouchOffset, y-yDragImageOffset-yDragTouchOffset, 0, 0);
		dragImage.setLayoutParams(lp);
	}
	
	private void editElement(long l) {
        Intent i = new Intent(mContext, ElementTab.class);
        // final long element_id = item.getID();
        i.putExtra(ProjectDbAdapter.KEY_ROWID, l);
        // i.putExtra(ProjectDbAdapter.KEY_PROJECT, mProjectId);
        
        mContext.startActivity(i);
        // mContext.startActivityForResult(i, ELEMENT_EDIT);		
	}
}
